var express = require('express');
var router = express.Router();
var superagent = require('superagent');
var logger = require('../log4j').logger;
var logger_error = require('../log4j').logger_error;

router.get('/neimeng', function(req, res, next) {
  var isApp = req.query.isApp;
  var info = {};
  var userInfo ={};
  var access_token = req.query.access_token || null;
  var openid = req.query.openid || null;
  var isPhone = false;
  var agentID = req.headers['user-agent'].toLowerCase().search(/(micromessenger)/);
  if(agentID>0){
    isPhone = true;
  }else{
    isPhone = false;
  }
  console.log(isPhone);
  if(isPhone && access_token == null){
     var state = encodeURIComponent(req.url.split('&openid')[0]);
     res.redirect(global.wechatURL + '/new/oauth/getAuthorizeURL?state=' + state + '&finalbase=' + global.browserURL+'/tv');
     return;
  }
  if(isPhone){
    superagent
    .get('https://api.weixin.qq.com/sns/userinfo')
    .query({
      access_token: access_token,
      openid: openid
    })
    .end(function(err, res4) {
      if (res4 !== undefined && res4.ok) {
        userInfo = JSON.parse(res4.text);
        var thisUrl = req.url;
        var shareUrl = encodeURIComponent((global.browserURL+'/tv'+thisUrl).split('#')[0]);
        console.log('shareUrl...'+(global.browserURL+'/tv'+thisUrl).split('#')[0]);
        superagent
        .get(global.wechatURL + '/wechat_api/jsconfig?url=' + shareUrl)
        .end(function(err, res2) {
          if (res2 !== undefined && res2.ok) {
            var targetType = 20;
            var targetId = global.targetId;
            console.log(global.baseURL + '/api/comments/?targetType=' + targetType + '&targetId=' + targetId);
            superagent
              .get(global.baseURL + '/api/comments/?targetType=' + targetType + '&targetId=' + targetId)
              .set({
                'DEVICE': 'weixin',
                'DEVICE_ID': openid
              })
              .end(function(err, res1) {
                if (res1 !== undefined && res1.ok) {
                  info = res1.body.result;
                  info.commentInfo = {id:targetId,type:targetType};
                  info.browserUrl = global.browserURL;
                  info.wxConfig = res2.body;
                  info.userInfo = userInfo;
                  info.isWechat = isPhone;
                  info.isApp = isApp;
                  res.render('tv/neimeng',info);
                }
                else {
                  console.error('请求数据错误!');
                  logger.error('请求数据错误。');
                  res.render('error', {message:'请求数据错误!!!!!!'});
                }
              });
          }
          else {
            console.error('微信分享api错误。');
            logger.error('微信分享api错误。');
            res.render('error', {message:'微信分享api错误。'});
          }
        });
      }
      else {
        console.error('请求数据错误!');
        logger.error('请求数据错误。');
      }
    })
  }else{
    var thisUrl = req.url;
    var shareUrl = encodeURIComponent((global.browserURL+'/tv'+thisUrl).split('#')[0]);
    superagent
    .get(global.wechatURL + '/wechat_api/jsconfig?url=' + shareUrl)
    .end(function(err, res2) {
      if (res2 !== undefined && res2.ok) {
        var targetType = 20;
        var targetId = global.targetId;
        superagent
          .get(global.baseURL + '/api/comments/?targetType=' + targetType + '&targetId=' + targetId)
          .set({
            'DEVICE': 'weixin',
            'DEVICE_ID': openid
          })
          .end(function(err, res1) {
            if (res1 !== undefined && res1.ok) {
              info = res1.body.result;
              info.commentInfo = {id:targetId,type:targetType};
              info.browserUrl = global.browserURL;
              info.wxConfig = res2.body;
              info.userInfo = userInfo;
              info.isWechat = isPhone;
              info.isApp = isApp;
              res.render('tv/neimeng',info);
            }
            else {
              console.error('请求数据错误!');
              logger.error('请求数据错误。');
              res.render('error', {message:'请求数据错误!!!!!!'});
            }
          });
      }
      else {
        console.error('微信分享api错误。');
        logger.error('微信分享api错误。');
        res.render('error', {message:'微信分享api错误。'});
      }
    });
  }
});

module.exports = router;
